﻿@{
    ViewData["Title"] = "DeathManagementAdd";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div style="margin-left: 20px; margin-top: 20px;">
    <button id="addRowBtn" class="layui-btn" style="background-color:red">
        <i class="layui-icon layui-icon-addition"></i>新增
    </button>
    <button id="saveBtn" class="layui-btn" style="background-color:red">
        <i class="layui-icon layui-icon-addition"></i>保存
    </button>
    <br />
    <div class="layui-inline" style="margin-top: 20px;">
        <form id="demo" class="layui-form" action="">
            <div class="layui-form-item" style="margin-left:-32px">
                <div class="layui-inline">
                    <label class="layui-form-label">
                        <span style="color:red">*</span>死亡日期
                    </label>
                    <div class="layui-input-inline layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="layui-icon layui-icon-date"></i>
                        </div>
                        <input type="text" name="deathDate" id="deathDate" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">羊只类型</label>
                    <div class="layui-input-block">
                        <input type="radio" name="sheepType" value="种母" title="种母" checked disabled>
                        <input type="radio" name="sheepType" value="种公" title="种公" disabled>
                        <input type="radio" name="sheepType" value="后裔" title="后裔" disabled>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">
                        单据号
                        <span style="margin-left: 10px;">-- --</span>
                    </label>
                </div>
                <div class="layui-inline">
                    <input type="text" name="reproductiveState" id="reproductiveState" style="display:none;">
                    <input type="text" name="sheepBir" id="sheepBir" style="display:none;">
                    <input type="text" name="deathDayAge" id="deathDayAge" style="display:none;">
                    <input type="text" name="deathMonthAge" id="deathMonthAge" style="display:none;">
                </div>
            </div>
        </form>
    </div>
    <table id="dataTable" class="layui-table" style="width: 98%;">
        <thead>
            <tr>
                <th style="width:120px;text-align: center;">序号</th>
                <th style="width:120px;text-align: center;">
                    <span style="color:red">*</span>羊只耳号
                </th>
                <th style="width:120px;text-align: center;">
                    <span style="color:red">*</span>死亡原因
                </th>
                <th style="width:120px;text-align: center;">品种</th>
                <th style="width:120px;text-align: center;">性别</th>
                <th style="width:120px;text-align: center;">当前栋舍</th>
                <th style="width:120px;text-align: center;">当前栏位</th>
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be dynamically added here -->
        </tbody>
    </table>
</div>
<style>
    /* 模拟layui的下拉框样式 */
    .select-wrapper {
        position: relative;
        display: inline-block;
        font-family: Arial, sans-serif;
        overflow: hidden;
        border: 1px solid #e6e6e6; /* 边框样式 */
        border-radius: 4px; /* 圆角 */
        background-color: #fff; /* 背景颜色 */
    }

        .select-wrapper select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            border: none;
            padding: 8px 10px;
            font-size: 14px;
            cursor: pointer;
            width: 200px;
            background: transparent; /* 透明背景 */
        }

        .select-wrapper::after {
            content: '\25BE'; /* 下三角形符号 */
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            pointer-events: none;
        }

        /* 根据选中状态改变样式 */
        .select-wrapper select:focus + ::after {
            color: #009688; /* 选中时的颜色 */
        }
</style>


<script>
    layui.use(['table', 'form', 'jquery'], function () {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        var layer = layui.layer;

        // 日期
        laydate.render({
            elem: '#deathDate',
            value: new Date(),
            isInitValue: true
        });

        $('#addRowBtn').on('click', function () {

            // 获取数据表格和行数
            const table = document.getElementById('dataTable');
            const numRows = table.rows.length;

            // 如果行数超过5，则禁止添加新行
            if (numRows > 1) {
                layer.msg('已达到最大行数限制，不能再添加新行！');
                return;
            }

            var rowCount = $('#dataTable tbody tr').length + 1; // 获取当前行数并加1作为新行的序号
            var newRowHtml = '<tr>' +
                '<td style="text-align: center;">' + rowCount + '</td>' + // 新增自增序号列

                `<td style="text-align: center;">
                                                                                    <div class="select-wrapper">
                                                                                    <select  name="earNumber" id="earNumber" lay-filter="earNumber" lay-verify="required">
                                                                                        <option value="">耳号</option>
                                                                                    </select>
                                                                                    </div>
                                                                                </td>` +

                `<td style="text-align: center;">
                                                                                <div class="select-wrapper">
                                                                                    <select  name="DeathCause" id="DeathCause" lay-filter="build" lay-verify="required">
                                                                                        <option value="">死亡原因</option>
                                                                                    </select>
                                                                                    </div>
                                                                                </td>` +

                `<td style="text-align: center;">
                                                                                <div class="select-wrapper">
                                                                                    <select name="sheepBreed" id="sheepBreed" lay-filter="column" lay-verify="required" disabled>
                                                                                        <option value="">品种</option>
                                                                                    </select>
                                                                                    </div>
                                                                              </td>` +

                `<td style="text-align: center;">
                                                                                    <div class="select-wrapper">
                                                                                         <select name="sheepGender" id="sheepGender" lay-filter="column" lay-verify="required" disabled>
                                                                                            <option value="">性别</option>
                                                                                            <option value="true">公</option>
                                                                                            <option value="false">母</option>
                                                                                        </select>
                                                                                        </div>
                                                                                  </td>` +

                '<td><input type="text" name="buildings" id="buildings" lay-verify="required" placeholder="" autocomplete="off" class="layui-input" disabled></td>' +
                '<td><input type="text" name="columns" id="columns" lay-verify="required" placeholder="" autocomplete="off" class="layui-input" disabled></td>' +
                '</tr>';

            $('#dataTable tbody').append(newRowHtml);

            //绑定耳号
            $(document).ready(function () {
                $.ajax({
                    url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        var select = $('#earNumber');
                        $.each(res, function (index, item) {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                            select.append(option);
                        });
                    },
                    error: function () {
                        // 处理 AJAX 请求失败的情况
                        console.error('Failed to fetch data for dropdown.');
                    }
                });
            });

            // 绑定品种
            $(document).ready(function () {
                $.ajax({
                    url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetSheepBreeds', // 后端枚举数据接口地址
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        $.each(res, function (index, item) {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.value).text(item.value);
                            $('#sheepBreed').append(option);
                        });
                        // 手动触发 layui 组件的渲染
                        layui.form.render('select');
                    },
                    error: function () {
                        // 处理 AJAX 请求失败的情况
                        console.error('Failed to fetch data for dropdown.');
                    }
                });
            });

            //绑定死亡原因
            $(document).ready(function () {
                $.ajax({
                    url: 'http://10.31.60.18:8000/SheepManagementGetRout/api/SheepManagement/GetDeathCause',
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        var select = $('#DeathCause');
                        $.each(res, function (index, item) {
                            // 使用正确的字段添加选项到下拉框中
                            var option = $('<option>').val(item.value).text(item.value);
                            select.append(option);
                        });
                        // 手动触发 layui 组件的渲染
                        layui.form.render('select');
                    },
                    error: function () {
                        // 处理 AJAX 请求失败的情况
                        console.error('Failed to fetch data for dropdown.');
                    }
                });
            });

            // 添加change事件监听器
            $('#earNumber').change(function () {
                var earNumber = $(this).val();
                $.ajax({
                    url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + earNumber,
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        console.log(res);
                        $("#sheepGender").val(res.sheepGender.toString());
                        $('.layui-input-block input[type="radio"]').each(function () {
                            if ($(this).val() === res.sheepType) {
                                $(this).prop('checked', true);
                            }
                        });
                        layui.form.render('radio');
                        $("#sheepBreed").val(res.sheepBreed);
                        $("#buildings").val(res.cottageId);
                        $("#columns").val(res.field);
                        $("#reproductiveState").val(res.reproductiveState);
                        $("#sheepBir").val(res.sheepBir);
                        $("#deathDayAge").val(res.dayAge);
                        $("#deathMonthAge").val(res.monthAge);
                    },
                    error: function () {
                        // 处理 AJAX 请求失败的情况
                        console.error('Failed to fetch data for dropdown.');
                    }
                });
            });
        });

        // 提交羊只死亡数据
        $('#saveBtn').on('click', function () {
            var formData = {
                earNumber: $('#earNumber').val(),
                deathCause: $("#DeathCause").val(),
                sheepGender: $("#sheepGender").val() == "true",
                sheepBreed: $("#sheepBreed").val(),
                cottageId: $("#buildings").val(),
                field: $("#columns").val(),
                sheepType: $("[name='sheepType']:checked").val(),
                deathDate: $("#deathDate").val(),
                reproductiveState:$("#reproductiveState").val(),
                sheepBir:$("#sheepBir").val(),
                deathDayAge: $("#deathDayAge").val(),
                deathMonthAge: $("#deathMonthAge").val(),
            }
            if (formData.earNumber == "") {
                layer.msg("请选择耳号");
                return;
            }
            if (formData.deathCause == "") {
                layer.msg("请选择死亡原因");
                return;
            }

            // 修改羊只档案在场状态数据
            var data = {
                EarNumber: formData.earNumber,
                PresenceStatus: "死亡离场"
            };

            $.ajax({
                type: 'post',
                //url: 'http://10.31.60.18:8000//BeginningSetRout/api/Beginning/BeginninCreate',
                url: 'http://10.31.60.18:8000/SheepManagementRout/api/SheepManagement/CreateSheepManagement',
                data: JSON.stringify(formData), // 将表单数据转为JSON格式
                contentType: 'application/json',
                success: function (response) {
                    if (response == 1) {
                        layer.msg('新增成功', function () {
                            // 修改羊只档案在场状态
                            updateStatus(data);
                        });
                    } else {
                        layer.msg('新增失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });
        });

        // 修改档案羊只在场状态
        function updateStatus(data) {
            $.ajax({
                url: `http://10.31.60.18:8000/ArchivesSetRout/api/Archives/ArchivesUpdateStatus`,
                type: 'put',
                data: JSON.stringify(data),
                contentType: 'application/json',
                success: function (res) {
                    window.location.href = '/SheepManagement/DeathManagement';
                },
                error: function () {
                    layer.msg('请求失败');
                }
            });
        }
    });

</script>
